package com.wangmengtao.upms.controller;

import com.wangmengtao.upms.dto.EasyuiTree;
import com.wangmengtao.upms.dto.ServerResponse;
import com.wangmengtao.upms.enums.ResponseCodeEnum;
import com.wangmengtao.upms.exception.UpmsException;
import com.wangmengtao.upms.util.ServerResponseUtil;
import com.wangmengtao.upms.util.TreeNodeUtil;
import com.wangmengtao.upms.model.UpmsDept;
import com.wangmengtao.upms.service.UpmsDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UpmsOrganizationController
 * @Description: TODO
 * @Author: WangMengtao
 * @Data: 2019/6/5 17:15
 * @Version: 1.0.0
 */
@RestController
public class UpmsDeptController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UpmsDeptService upmsDeptService;

    @PostMapping(value = "/depts")
    public ServerResponse<String> create(@RequestBody UpmsDept upmsDept) {
        logger.info("name :" + upmsDept.getName() + " Description :" + upmsDept.getDescription() + "ParentId:" + upmsDept.getParentId());
        if (upmsDeptService.insert(upmsDept) >= 1) {
            return ServerResponseUtil.success("添加成功");
        } else {
            return ServerResponseUtil.error(201, "添加失败");
        }

    }

    @DeleteMapping(value = "/depts/{id}")
    public Object deleteById(@PathVariable("id") Long id) {
        return upmsDeptService.deleteById(id);
    }

    @PutMapping(value = "/depts")
    public Object update(@RequestBody UpmsDept upmsDept) {
        if (upmsDept.getId() == null) {
            throw new UpmsException(ResponseCodeEnum.NO_ID);
        }
        return upmsDeptService.update(upmsDept);
    }

    @GetMapping(value = "/depts/{id}")
    public Object getByid(@PathVariable("id") Long id) {
        return upmsDeptService.getById(id);
    }

    @GetMapping(value = "/depts")
    public Object list() {
        return upmsDeptService.list();
    }

    @GetMapping(value = "/depts/tree")
    public List<EasyuiTree> tree() {
        List<EasyuiTree> easyuiTrees = new ArrayList<EasyuiTree>();
        List<UpmsDept> upmsDepts = upmsDeptService.list();
        if (upmsDepts == null) {
            return easyuiTrees;
        }
        for (UpmsDept upmsDept : upmsDepts) {
            EasyuiTree easyuiTree = new EasyuiTree();
            easyuiTree.setId(upmsDept.getId());
            easyuiTree.setText(upmsDept.getName());
            easyuiTree.setParentId(upmsDept.getParentId());
            easyuiTrees.add(easyuiTree);
        }
        return TreeNodeUtil.getFatherNode(easyuiTrees);
    }

}
